package com.example.taobao

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.View
import android.widget.Toast
import androidx.recyclerview.widget.GridLayoutManager
import kotlinx.android.synthetic.main.activity_searched.*
import java.io.BufferedReader
import java.io.InputStreamReader
import java.lang.Exception
import java.net.HttpURLConnection
import java.net.URL
import kotlin.concurrent.thread

class SearchedActivity : AppCompatActivity() {
    private val search = "search"
    var flag_xl : Int = 0

    var flag_price: Int = 0

    private var searched_List = ArrayList<searchedData>()

    var layoutManager : GridLayoutManager? = null
    var adapter : searchedAdapter? = null
    val handle = @SuppressLint("HandlerLeak")
    object : Handler()
    {
        override fun handleMessage(msg: Message) {
            searched_List = msg.obj as ArrayList<searchedData>
            layoutManager = GridLayoutManager(this@SearchedActivity, 2)
            searched_card.layoutManager = layoutManager
            adapter = searchedAdapter(this@SearchedActivity, searched_List)
            searched_card.adapter = adapter
            adapter?.setOnItemClickListener(object: searchedAdapter.OnItemClickListener {
                override fun onItemClick(view: View, position: Int) {

                    showToast("click " + position + " item")
                    val ins = Intent(this@SearchedActivity, MainDetails::class.java)
                    ins.putExtra("id", searched_List[position].id)
                    startActivity(ins)
                }

            })
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_searched)

        val content: String? = intent.getStringExtra("content")
        if (content != null) {
            initSearch(content)
        }


        /* layoutManager = GridLayoutManager(this, 2)
         searched_card.layoutManager = layoutManager
         adapter = searchedAdapter(this, searched_List)
         searched_card.adapter = adapter*/




        s_sell.setOnClickListener {
            if(flag_xl == 0 )
            {
                s_sell.setTextColor(Color.RED)
                searched_List.sortBy { it.pay_num }
                flag_xl++
            } else if( flag_xl == 1)
            {
                s_sell.setTextColor(Color.BLUE)
                searched_List.sortByDescending { it.pay_num }
                flag_xl = 0
            }
            flag_price = 0
            s_price.setTextColor(Color.WHITE)
            refresh()
        }

        s_price.setOnClickListener {
            if(flag_price == 0 )
            {
                s_price.setTextColor(Color.RED)
                searched_List.sortBy { it.price }
                flag_price++
            } else if( flag_price == 1)
            {
                s_price.setTextColor(Color.BLUE)
                searched_List.sortByDescending { it.price }
                flag_price = 0
            }
            flag_xl = 0;
            s_sell.setTextColor(Color.WHITE)
            refresh()

        }


    }

    private fun showToast(message: String){
        Toast.makeText(applicationContext,message, Toast.LENGTH_SHORT).show()
    }




    /* private fun init_Searched(){
         searched_List.clear()
         repeat(20 ){
             searched_List.add(searchedData(R.mipmap.test, "美国西海岸最牛的新冠病毒套餐", "天堂太远 | 美国太近", 199, 1930))
         }

         repeat(20 ){
             searched_List.add(searchedData(R.mipmap.test, "美国西海岸最牛的新冠病毒套餐", "天堂太远 | 美国太近", 400, 3))
         }

     }*/


    private fun refresh(){

        layoutManager = GridLayoutManager(this, 2)
        searched_card.layoutManager = layoutManager
        adapter = searchedAdapter(this, searched_List)
        searched_card.adapter = adapter
    }

    private fun initSearch(keys : String)
    {
        val us = "http://192.168.43.140:8080/aaa_war_exploded/search.jsp?name=" + keys
        thread {
            var url = URL(us)
            //var url = URL("https://www.baidu.com")
            val connection = url.openConnection() as HttpURLConnection
            try {
                val response = StringBuilder()
                connection.connectTimeout = 8000
                connection.readTimeout = 8000
                connection.requestMethod = "POST"

                connection.setRequestProperty("Accept-Charset", "UTF-8" )
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
                connection.connectTimeout = 8000
                connection.readTimeout = 8000
                val input = connection.inputStream
                val reader = BufferedReader(InputStreamReader(input) )

                var src : String = ""
                var id : Int = 0
                var names:String = ""
                var describe:String = ""
                var prices:String = ""
                var sales:String= ""
                var i = 0

                var meg : ArrayList<searchedData> = ArrayList<searchedData>()

                reader.use {
                    reader.forEachLine {
                        if(it.length > 0) {
                            if( i == 0)
                                id = it.toInt()
                            else if( i == 1)
                                src = it
                            else if ( i == 2)
                                names = it
                            else if( i == 3)
                                describe = it
                            else if(i  == 4)
                                prices = it
                            else if( i == 5)
                            {
                                sales = it
                                i = -1
                                meg.add(searchedData(id, src, names, describe, prices , sales))
                            }
                            i++
                        }
                    }
                }

                searched_List = meg
                val msg = Message()
                msg.obj = meg
                handle.sendMessage(msg)


                //  showResponse(response.toString() )
            } catch (e: Exception )
            {
                e.printStackTrace();
            } finally {
                connection.disconnect()
            }
        }

    }
}